<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Message_m extends FOX_Model
{

	function __construct ()
	{
		parent::__construct();
	}

    //寻找默认地址消息
    function get_massage_dress($user_id){
        $query = $this->db->select('*')->from('messages')->where('message_type',5)->where('message_to_uid',$user_id)->get();
        return $query->result_array();
    }

    //找出用户未看的提醒
    public function all_find_message($message_to_uid)
    {
        $this->db->select('*');
        $this->db->from('messages');
        $this->db->where('message_to_uid',$message_to_uid);
        $this->db->where('message_lock',1);
        $query = $this->db->get();
        if($query->num_rows() > 0){
            return $query->result_array();
        }        
    }

    //计算用户的消息总数
    public function count_user_message($message_to_uid){
        $this->db->select('message_id');
        $this->db->from('messages');
        $this->db->where('message_to_uid',$message_to_uid);
        $total=$this->db->count_all_results();
        return $total;
    }

    public function user_find_message($page=0,$limit=4,$message_to_uid)
    {
        $start = $page*$limit;
        $this->db->select('*');
        $this->db->from('messages');
        $this->db->where('message_to_uid',$message_to_uid);
        $this->db->order_by('message_time','desc');
        $this->db->limit($limit,$start);
        $query = $this->db->get();
        if($query->num_rows() > 0){
            return $query->result_array();
        }        
    }

    public function update_user_message($message_to_uid)
    {
        $this->db->set('message_lock',0,false)->where('message_to_uid',$message_to_uid)->update('messages');
    }

    public function update_message($id,$data){

        $this->db->where('message_id',$id);
        $this->db->update('messages', $data);
        return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
    }

    public function add_massage($data){

        $this->db->insert('messages',$data);
        return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
    }
    //删除消息
    public function del_user_message_by_id($id){
        $this->db->where('message_id',$id)->delete('messages');
        return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
    }

    public function get_new_message($uid){
        $this->db->select('message_txt');
        $this->db->from('messages');
        $this->db->where('message_to_uid',$uid);
        $this->db->order_by('message_time','desc');
        $query = $this->db->get();
        if($query->num_rows() > 0){
            $res =  $query->row_array();
            return $res['message_txt'];
        }
    }
}
